package com.atguigu.tingshu.account;

import cn.hutool.core.collection.CollectionUtil;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * ClassName: AccountReceiver
 * Package: com.atguigu.tingshu.account
 * Description:
 *
 * @Author 咚咚小圆帽
 * @Create 2025/6/29 18:08
 * @Version 1.0
 */
@Slf4j
@Component
public class AccountReceiver {

    @Autowired
    private UserAccountService userAccountService;

    /**
     * 监听首次登录消息，初始化用户账户
     *
     * @param mapData
     * @param message
     * @param channel
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = MqConst.QUEUE_USER_REGISTER, durable = "true"),
                    exchange = @Exchange(value = MqConst.EXCHANGE_USER, durable = "true"),
                    key = {MqConst.ROUTING_USER_REGISTER}
            )
    )
    @SneakyThrows
    public void initUserAccount(Map<String, Object> mapData, Message message, Channel channel) {
        if (CollectionUtil.isNotEmpty(mapData)) {
            log.info("[账户服务]监听到初始化账户消息:{}", mapData);
            userAccountService.saveUserAccount(mapData);
        }

        //手动确认： 参数1：消息的索引值，参数2：是否批量处理
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

    }


}
